#include "mainwindow.h"
#include "widgets/dashboardwidget.h"
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QRandomGenerator>
#include <QMessageBox>
#include <QSet>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    QLabel *title = new QLabel("温室大棚智能监控系统", this);
    title->setAlignment(Qt::AlignCenter);
    title->setStyleSheet("font-size: 24px; font-weight: bold;");
    mainLayout->addWidget(title);

    dashboard = new DashboardWidget(this);
    mainLayout->addWidget(dashboard);

    setCentralWidget(centralWidget);
    setWindowTitle("温室大棚智能监控系统");
    resize(800, 600);

    // 初始化环境参数
    envData["温度(℃)"] = 25.0;
    envData["湿度(%)"] = 60.0;
    envData["光照强度(lx)"] = 10000.0;
    envData["土壤墒情(%)"] = 40.0;

    // 初始化参数阈值
    paramThresholds["温度(℃)"] = qMakePair(15.0, 35.0);
    paramThresholds["湿度(%)"] = qMakePair(30.0, 80.0);
    paramThresholds["光照强度(lx)"] = qMakePair(5000.0, 20000.0);
    paramThresholds["土壤墒情(%)"] = qMakePair(20.0, 60.0);

    // 定时器每200ms刷新一次（5Hz）
    refreshTimer = new QTimer(this);
    connect(refreshTimer, &QTimer::timeout, this, &MainWindow::updateEnvData);
    refreshTimer->start(200);
}

MainWindow::~MainWindow()
{
}

void MainWindow::updateEnvData()
{
    // 模拟数据变化
    envData["温度(℃)"] += (QRandomGenerator::global()->generateDouble() - 0.5) * 0.4; // -0.2~+0.2
    envData["湿度(%)"] += (QRandomGenerator::global()->generateDouble() - 0.5) * 1.0; // -0.5~+0.5
    envData["光照强度(lx)"] += (QRandomGenerator::global()->generateDouble() - 0.5) * 100.0; // -50~+50
    envData["土壤墒情(%)"] += (QRandomGenerator::global()->generateDouble() - 0.5) * 0.6; // -0.3~+0.3

    // 更新仪表盘显示和告警
    for (auto it = envData.begin(); it != envData.end(); ++it) {
        dashboard->setParameter(it.key(), it.value());

        // 阈值判断
        bool overLimit = false;
        if (paramThresholds.contains(it.key())) {
            double minV = paramThresholds[it.key()].first;
            double maxV = paramThresholds[it.key()].second;
            if (it.value() < minV || it.value() > maxV) {
                overLimit = true;
                dashboard->setParameterHighlight(it.key(), true);
                // 弹窗（只弹一次，直到恢复正常）
                if (!alarmedParams.contains(it.key())) {
                    alarmedParams.insert(it.key());
                    QMessageBox::warning(this, "参数超限告警",
                        QString("%1 超出安全范围！当前值：%2").arg(it.key()).arg(it.value(), 0, 'f', 2));
                }
            } else {
                dashboard->setParameterHighlight(it.key(), false);
                alarmedParams.remove(it.key());
            }
        }
    }
} 